package org.redis.utils;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadPoolUtils
 *
 * @author grl
 * @date 2024/1/26
 */
public class ThreadPool {

    private ThreadPool() {
    }

    /**
     * 存放任务的对象的队列
     */
    private static final LinkedBlockingDeque<Runnable> QUEUE = new LinkedBlockingDeque<>(1000);
    /**
     * 线程名称
     */
    private static final AtomicInteger atomic = new AtomicInteger(0);
    /**
     * 创建线程工厂
     */
    private static final ThreadFactory factory = (r) -> {
        Thread thread = new Thread(r);
        thread.setName("thread_pools_" + atomic.getAndIncrement());
        return thread;
    };
    /**
     * 创建线程池
     */
    private static ThreadPoolExecutor executor;

    /**
     * 获取线程池
     *
     * @return
     */
    public static ThreadPoolExecutor getExecutor() {
        if (executor == null) {
            synchronized (ThreadPool.class) {
                if (executor == null) {
                    executor = new ThreadPoolExecutor(1, 4, 60, TimeUnit.SECONDS, QUEUE, factory,
                            new ThreadPoolExecutor.DiscardPolicy());
                }
            }
        }
        return executor;
    }

}
